package com.battery.service.impl;

import com.battery.dao.DeviceDao;
import com.battery.dao.MerChantDao;
import com.battery.dao.PowerBankDao;
import com.battery.pojo.Device;
import com.battery.pojo.Order;
import com.battery.pojo.PowerBank;
import com.battery.service.DeviceService;
import com.battery.service.OrderService;
import com.battery.util.result.Result;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;

import static com.battery.netty.ServerHandler.CHANNEL_HANDLER_CONTEXT_MAP;

@Service
@Transactional
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private DeviceDao deviceDao;
    @Autowired
    private MerChantDao merChantDao;
    @Autowired
    private OrderService orderService;
    @Autowired
    private PowerBankDao powerBankDao;

    @Override
    public Result addDevice(Device device) {
        try {
            if(merChantDao.findOne(device.getMer_id())!=null)
                deviceDao.insertDevice(device);
            else return Result.error().message("No such a Merchant");
        } catch (DuplicateKeyException e){
            return Result.error().message("重复主键"+e.toString());

        } catch (Exception e){
            return Result.error().message("未知错误："+e.toString());
        }
        return Result.ok().message("插入成功");
    }

    @Override
    public Result queryAllDevice() {
        try {
            return Result.ok().data("deviceList",deviceDao.getAllDevice());
        }catch (Exception e){
            return Result.error().message("未知错误："+e.toString());
        }
    }

    @Override
    public Result updateDevice(Device device) {
        try {
            if(deviceDao.updateDevice(device)!=0){
                return Result.ok().message("修改成功");
            }
        }catch (Exception e){
            return Result.error().message("修改失败："+e.toString());
        }
        return Result.error();
    }

    @Override
    public Result updateDevice(HashMap hashMap) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        try {
            Device device = (Device) this.getDeviceById(Integer.parseInt((String) hashMap.get("STATIONID"))).getData().get("device");
            if (device == null) {
                CHANNEL_HANDLER_CONTEXT_MAP.get((String) hashMap.get("STATIONID")).write("ERRORCODE:1;ERRMSG:NO SUCH A DEVICE;STATIONID:" + Integer.parseInt((String) hashMap.get("STATIONID")) + ";TIMESTAMP:" + timestamp.toString() + ";ACK:sync_setting\\r\\n");
            }
            device.setDevice_can_lent(Integer.parseInt((String) hashMap.get("USABLE_BATTERY")));
            device.setDevice_can_return(Integer.parseInt((String) hashMap.get("EMPTY_SLOT_COUNT")));
            device.setDevice_num(Integer.parseInt((String) hashMap.get("TOTAL")));
            this.updateDevice(device);
            CHANNEL_HANDLER_CONTEXT_MAP.get((String) hashMap.get("STATIONID")).write("ERRORCODE:0;ERRMSG:SUCCESS;STATIONID:" + Integer.parseInt((String) hashMap.get("STATIONID")) + ";TIMESTAMP:" + timestamp.toString() + ";ACK:sync_setting\\r\\n");
            CHANNEL_HANDLER_CONTEXT_MAP.get((String) hashMap.get("STATIONID")).flush();
            return Result.ok();
        }
        catch (Exception e){
//            CHANNEL_HANDLER_CONTEXT_MAP.get((String) hashMap.get("STATIONID")).write("ERRORCODE:2;ERRMSG:"+e.toString()+";STATIONID:" + Integer.parseInt((String) hashMap.get("STATIONID")) + ";TIMESTAMP:" + timestamp.toString() + ";ACK:sync_setting\\r\\n");
            return Result.error();
        }
    }

    @Override
    public Result getDeviceByKey(String key) {
        try {
            List<Device> device=deviceDao.getDeviceByKey(key);
            if(device!=null)
                return Result.ok().data("device",device);
            else
                return Result.error().message("无该设备");

        }catch (Exception e){
            return Result.error().message("查找失败");
        }
    }

    @Override
    public Result getDeviceById(int id) {
        try {
            Device device=deviceDao.selectDeviceById(id);
            if(device!=null){
                return Result.ok().data("device",device);
            }
            return Result.error().message("no such a device");
        }catch (Exception e){
            return Result.error().message("查找失败"+e.toString());
        }
    }

    @Override
    public Result deviceLogin(HashMap hashMap, ChannelHandlerContext ctx) {
        if(CHANNEL_HANDLER_CONTEXT_MAP.get(hashMap.get("STATIONID"))!=null){
            CHANNEL_HANDLER_CONTEXT_MAP.get(hashMap.get("STATIONID")).write("ERRORCODE:1; ERRMSG:DEVICE IS ALREADY LOGINED;STATIONID:"+hashMap.get("STATIONID")+";ACK:login\\r\\n");
            return Result.error();
        }
        CHANNEL_HANDLER_CONTEXT_MAP.put((String) hashMap.get("STATIONID"),ctx);
        if (CHANNEL_HANDLER_CONTEXT_MAP.get(hashMap.get("STATIONID"))!=null)
        {
            CHANNEL_HANDLER_CONTEXT_MAP.get(hashMap.get("STATIONID")).write("ERRORCODE:0; ERRMSG:SUCCESS;STATIONID:"+hashMap.get("STATIONID")+";ACK:login\\r\\n");
        }
        return Result.ok();
    }

    @Override
    public Result lentBattery(Order order) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Device device= deviceDao.selectDeviceById(order.getDevice_id());
        if(device.getDevice_can_lent()==0){
            return Result.error().message("没有剩余的充电宝了");
        }
        System.out.println();
        if(orderService.addOrder(order).getCode()==20000){
            CHANNEL_HANDLER_CONTEXT_MAP.get(String.valueOf(order.getDevice_id())).write("EVENT_CODE:rent;STATIONID:"+order.getDevice_id()+"; SLOT:1;ORDERID:"+order.getOrder_id()+";TIMESTAMP:"+timestamp.toString()+"\\r\\n");
            CHANNEL_HANDLER_CONTEXT_MAP.get(String.valueOf(order.getDevice_id())).flush();
            return Result.ok();
        }
        else {
            return Result.error();
        }
    }

    @Override
    public Result updateOrder(HashMap<String, String> hashMap) {
        Order order = (Order) orderService.queryOrder(Integer.parseInt(hashMap.get("ORDERID"))).getData().get("order");
        Device device = (Device) this.getDeviceById(Integer.parseInt((String) hashMap.get("STATIONID"))).getData().get("device");
        device.setDevice_can_lent(Integer.parseInt( hashMap.get("USABLE_BATTERY")));
        device.setDevice_can_return(Integer.parseInt(hashMap.get("EMPTY_SLOT_COUNT")));
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        if (hashMap.get("STATUS") == "0") {
            this.updateDevice(device);
            order.setpb_id(Integer.parseInt(hashMap.get("ID")));
            order.setOrder_status("4");//代表已经拿了充电宝
            orderService.modifyOrder(order);
            if(CHANNEL_HANDLER_CONTEXT_MAP.get(String.valueOf(order.getDevice_id()))==null)
                return Result.error();
            CHANNEL_HANDLER_CONTEXT_MAP.get(String.valueOf(order.getDevice_id())).write("ERRORCODE:0;ERRMSG:none;STATIONID:"+order.getDevice_id()+"; TIMESTAMP:"+timestamp.toString()+";ACK:rent_confirm\r\n");
            CHANNEL_HANDLER_CONTEXT_MAP.get(String.valueOf(order.getDevice_id())).flush();
            return Result.ok();
        }
        else {
            if(CHANNEL_HANDLER_CONTEXT_MAP.get(String.valueOf(order.getDevice_id()))==null)
                return Result.error();
            order.setOrder_status("5");//代表订单已经没有充电宝了

            CHANNEL_HANDLER_CONTEXT_MAP.get(String.valueOf(order.getDevice_id())).write("ERRORCODE:0;ERRMSG:none;STATIONID:"+order.getDevice_id()+"; TIMESTAMP:"+timestamp.toString()+";ACK:rent_confirm\r\n");
            CHANNEL_HANDLER_CONTEXT_MAP.get(String.valueOf(order.getDevice_id())).flush();
            return Result.ok();
        }
    }

    @Override
    public Result returnBattery(HashMap<String, String> hashMap) {
        System.out.println(hashMap);
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Device device=deviceDao.selectDeviceById(Integer.parseInt(hashMap.get("STATIONID")));
        device.setDevice_can_lent(Integer.parseInt( hashMap.get("USABLE_BATTERY")));
        device.setDevice_can_return(Integer.parseInt(hashMap.get("EMPTY_SLOT_COUNT")));
        this.updateDevice(device);
        if(CHANNEL_HANDLER_CONTEXT_MAP.get(String.valueOf(device.getDevice_id()))==null)
            return Result.error();
        CHANNEL_HANDLER_CONTEXT_MAP.get(String.valueOf(device.getDevice_id())).write("ERRORCODE:0;ERRMSG:none;STATIONID:"+device.getDevice_id()+ ";ID:2808000135;TIMESTAMP:"+timestamp+";ACK:return_back\\r\\n");
        CHANNEL_HANDLER_CONTEXT_MAP.get(String.valueOf(device.getDevice_id())).flush();
        PowerBank powerBank= powerBankDao.findByPb_Id(Integer.parseInt(hashMap.get("ID")));
        powerBank.setPb_location(Integer.parseInt(hashMap.get("SLOT")));
        powerBankDao.updatePowerBank(powerBank);
        return Result.ok();
    }
    @Override
    public Result popBattery(int slot, int deviceId) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        ChannelHandlerContext ctx=CHANNEL_HANDLER_CONTEXT_MAP.get(String.valueOf(deviceId));
        if (ctx==null)
            return Result.error().message("设备未连接");
        ctx.write("EVENT_CODE:popup;STATIONID:"+deviceId+";SLOT:"+slot+";TIMESTAMP:" +timestamp+"\\r\\n");
        ctx.flush();
        return Result.ok().message("弹出成功");
    }

    @Override
    public Result popupConfirm(HashMap<String, String> hashMap) {
        if (hashMap.get("STATUS") == "0") {
            Device device = deviceDao.selectDeviceById(Integer.parseInt(hashMap.get("STATIONID")));
            device.setDevice_can_lent(Integer.parseInt(hashMap.get("USABLE_BATTERY")));
            device.setDevice_can_return(Integer.parseInt(hashMap.get("EMPTY_SLOT_COUNT")));
            this.updateDevice(device);
            return Result.ok();
        }
        return Result.error();
    }
}
